package com.zmn.oms.admin.controller.chan;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.constant.OrderClueConsts;
import com.zmn.oms.common.constant.OrderPremissionConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.enums.ChannelFacade;
import com.zmn.oms.common.exception.chan.ChannelFacadeException;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.model.dto.chan.OrderClueDetailDTO;
import com.zmn.oms.model.dto.chan.OrderClueDetailListQuery;
import com.zmn.oms.model.entity.chan.OrderClueDetail;
import com.zmn.oms.model.vo.chan.OrderClueDetailVO;
import com.zmn.oms.zmn.business.interfaces.chan.FacadeOrderClueBService;
import com.zmn.oms.zmn.business.interfaces.chan.FacadeOrderClueDetailBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/14 17:45
 */
@Controller
@RequestMapping("/chan/clueDetail")
public class OrderClueDetailController extends OmsBaseController {

    @Autowired
    private FacadeOrderClueDetailBService facadeOrderClueDetailBService;
    @Autowired
    private FacadeOrderClueBService facadeOrderClueBService;
    @Autowired
    private ZsOrderWorkQueryBService zsOrderWorkQueryBService;


    @RequestMapping(value = "/list")
    public ModelAndView list(ModelAndView mv) {
        mv.setViewName("chan/clue_detail/list");
        // 下单日期
        mv.addObject("receiveTimeStart",
                DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), -1), DateUtil.FORMAT_DATE));
        mv.addObject("receiveTimeEnd",
                DateUtil.toString(DateUtil.getNow(), DateUtil.FORMAT_DATE));

        // 状态
        mv.addObject("facadeList", ChannelFacade.getChannelFacadeList());
        // 城市ID
        mv.addObject("cityList", super.getCityListByDept());
        // 状态
        mv.addObject("stateList", OrderClueConsts.getOrderClueDetailStateList());

        return mv;
    }

    /**
     * 查询委托单列表 ajax
     */
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody OrderClueDetailListQuery query) {
        try {
            logger.debug("查询线索单：[{}]", JSON.toJSONString(query));

            processQuery(query);
            List<OrderClueDetail> orderClueDetails = facadeOrderClueDetailBService.listOrderClueDetails(query);
            logger.info("查询线索单结果：OrderClueDetail=[{}]", JSON.toJSONString(orderClueDetails));



            List<OrderClueDetailVO> orderClueDetailVOs = new LinkedList<>();
            if (CollectionUtils.isNotEmpty(orderClueDetails)) {
                for (OrderClueDetail item : orderClueDetails) {
                    OrderClueDetailVO detailVO = BeanMapper.map(item, OrderClueDetailVO.class);
                    if (detailVO.getFacadeId() != null) {
                        detailVO.setFacadeName(ChannelFacade.getByFacadeId(detailVO.getFacadeId()).getName());
                    }
                    detailVO.setStateName(OrderClueConsts.getOrderClueDetailStateName(item.getState()));
                    orderClueDetailVOs.add(detailVO);
                }

                processUserInfoPermiss(orderClueDetailVOs, OrderPremissionConsts.MODULE_ID_ZS);
            }

            LayuiTableDO<OrderClueDetailVO> data = new LayuiTableDO();
            data.setCount(query.getTotalCount());
            data.setData(orderClueDetailVOs);
            logger.info("查询线索单结果：LayuiTableResponseDTO=[{}]", JSON.toJSONString(data));

            return ResultDTO.success(data);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }
    }

    private void processUserInfoPermiss(List<OrderClueDetailVO> orderClueDetailVOs, Integer moduleId) {
        // boolean hasUserPhone = StaffAdminService.isPermitted(OrderPremissionConsts.CCD_USER_PHONE);
        // boolean hasUserInfo = StaffAdminService.isPermitted(OrderPremissionConsts.CCD_USER_ADDRESS);
        boolean hasUserPhone = false;
        boolean hasUserInfo = false;

        logger.debug("processUserInfoPermiss: hasUserInfo[{}]=[{}], hasUserPhone[{}]=[{}]",
                OrderPremissionConsts.CCD_USER_PHONE, hasUserPhone, OrderPremissionConsts.CCD_USER_ADDRESS, hasUserInfo);

        for (OrderClueDetailVO item : orderClueDetailVOs) {
            if (!hasUserInfo && StringUtils.isNotBlank(item.getAddressInfo())) {
                item.setAddressInfo("****");
            }
            if (!hasUserPhone && StringUtils.isNotBlank(item.getContactPhone())) {
                item.setContactPhone(MobileUtil.formatHideTel(item.getContactPhone()));
            }
        }
    }


    /**
     * 查询委托单列表 ajax
     */
    @PostMapping(value = "/apply2ZmnOrder")
    @ResponseBody
    public ResultDTO apply2ZmnOrder(OrderClueDetailDTO detailDTO) {
        try {
            OrderClueDetail detail = facadeOrderClueDetailBService.apply2ZmnOrder(detailDTO);
            OrderClueDetailVO detailVO = BeanMapper.map(detail, OrderClueDetailVO.class);
            detailVO.setStateName(OrderClueConsts.getOrderClueDetailStateName(detail.getState()));
            return ResultDTO.success(detailVO);
        } catch (ChannelFacadeException e) {
            logger.error(e.getMessage(), e);
            boolean isAppLied = Objects.equals(StatusConsts.STATUS_SUCCESS_NEXT, e.getCode());
            if (isAppLied) {
                OrderClueDetail detail = facadeOrderClueDetailBService.findOrderClueDetailByClueId(detailDTO.getClueId());
                OrderClueDetailVO detailVO = BeanMapper.map(detail, OrderClueDetailVO.class);
                detailVO.setStateName(OrderClueConsts.getOrderClueDetailStateName(detail.getState()));

                ResultDTO fail = ResultDTO.fail(StatusConsts.STATUS_SUCCESS_NEXT, e.getMessage());
                fail.setData(detailVO);
                return fail;
            }
            return ResultDTO.fail(StatusConsts.STATUS_ERROR, e.getMessage());
        }
    }

    /**
     * 查询委托单列表 ajax
     */
    @PostMapping(value = "/ignoreOrderClueDetail")
    @ResponseBody
    public ResultDTO ignoreOrderClueDetail(OrderClueDetailDTO detailDTO) {
        try {
            OrderClueDetail detail = facadeOrderClueDetailBService.ignoreOrderClueDetail(detailDTO);
            OrderClueDetailVO detailVO = BeanMapper.map(detail, OrderClueDetailVO.class);
            detailVO.setStateName(OrderClueConsts.getOrderClueDetailStateName(detail.getState()));
            return ResultDTO.success(detailVO);
        } catch (ChannelFacadeException e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 查询委托单列表 ajax
     */
    @PostMapping(value = "/resetState2Pending")
    @ResponseBody
    public ResultDTO resetState2Pending(OrderClueDetailDTO detailDTO) {
        try {
            OrderClueDetail detail = facadeOrderClueDetailBService.resetState2Pending(detailDTO);
            OrderClueDetailVO detailVO = BeanMapper.map(detail, OrderClueDetailVO.class);
            detailVO.setStateName(OrderClueConsts.getOrderClueDetailStateName(detail.getState()));
            return ResultDTO.success(detailVO);
        } catch (ChannelFacadeException e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 解析查询参数
     * @param query
     */
    private void processQuery(OrderClueDetailListQuery query) {
        query.setPageSize(15);
        // 下单时间
        if (StringUtils.isNotBlank(query.getReceiveTime())) {
            String receiveTimeStr = query.getReceiveTime();
            String[] arr = receiveTimeStr.split(",");
            String strBegin = null;
            String strEnd = null;

            if (arr.length == 1) {
                if (receiveTimeStr.endsWith(",")) {
                    strBegin = arr[0];
                }
                else {
                    strEnd = arr[0];
                }
            }
            else if (arr.length == 2) {
                strBegin = arr[0];
                strEnd = arr[1];
            }

            if ((StringUtils.isNotBlank(strBegin))) {
                query.setCreateTimeBegin(DateUtil.parse(strBegin));
            }
            if ((StringUtils.isNotBlank(strEnd))) {
                query.setCreateTimeEnd(DateUtil.parse(strEnd));
            }
        }

        if (query.getCreateTimeBegin() == null) {
            String createTimeBegin = DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), -1), DateUtil.FORMAT_DATE);
            query.setCreateTimeBegin(DateUtil.parse(createTimeBegin));
        }
    }
}
